<template>
  <div class="contract-sign-container">
    <div class="header">
      <div class="header-content d-flex justify-content-between align-items-center">
        <h2>确认签订合同</h2>
        <button @click="goBack" class="btn btn-secondary">
          <i class="fa fa-arrow-left mr-2"></i>返回上一级
        </button>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-indicator text-center py-12">
      <div class="spinner inline-block"></div>
      <p class="mt-3 text-gray-600">加载合同中...</p>
    </div>

    <!-- 错误消息 -->
    <div v-if="errorMessage" class="error-message bg-red-50 border-l-4 border-red-400 text-red-700 p-4 mb-6">
      <div class="flex">
        <i class="fa fa-exclamation-circle mr-3 mt-1"></i>
        <span>{{ errorMessage }}</span>
      </div>
    </div>

    <div v-if="contract && !loading" class="card mt-4 shadow-sm">
      <div class="card-body">
        <!-- 合同详情 - 上半部分 -->
        <h3 class="contract-name text-xl font-bold text-gray-800 mb-4">{{ contract.name }}</h3>
        <div class="contract-info grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
          <p class="flex items-start">
            <span class="font-medium text-gray-700 min-w-[100px]">合同ID:</span>
            <span class="ml-2 text-gray-600">{{ contract.id }}</span>
          </p>
          <p class="flex items-start">
            <span class="font-medium text-gray-700 min-w-[100px]">客户:</span>
            <span class="ml-2 text-gray-600">{{ contract.customer?.companyName || '未选择' }}</span>
          </p>
          <p class="flex items-start">
            <span class="font-medium text-gray-700 min-w-[100px]">项目经理:</span>
            <span class="ml-2 text-gray-600">{{ projectManagerName }}</span>
          </p>
          <p class="flex items-start">
            <span class="font-medium text-gray-700 min-w-[100px]">状态:</span>
            <span class="ml-2 px-2 py-1 rounded-full text-xs" :class="getStatusClass(contract.status)">{{ formatStatus(contract.status) }}</span>
          </p>
          <p class="flex items-start">
            <span class="font-medium text-gray-700 min-w-[100px]">创建时间:</span>
            <span class="ml-2 text-gray-600">{{ formatDate(contract.createTime) }}</span>
          </p>
          <p class="flex items-start">
            <span class="font-medium text-gray-700 min-w-[100px]">更新时间:</span>
            <span class="ml-2 text-gray-600">{{ formatDate(contract.updateTime) }}</span>
          </p>
        </div>

        <div class="clauses-section mt-6">
          <h4 class="text-lg font-semibold text-gray-700 mb-3">条款列表</h4>
          <div v-if="clauses.length > 0" class="clauses-list">
            <div class="space-y-3">
              <div v-for="clause in clauses" :key="clause.id" class="p-4 border border-gray-200 rounded-lg bg-gray-50 hover:bg-gray-100 transition-colors">
                <p class="text-gray-700"><strong>内容:</strong> {{ clause.content }}</p>
              </div>
            </div>
          </div>
          <div v-else class="empty-message text-center py-8 text-gray-500">
            <i class="fa fa-info-circle text-2xl mb-2"></i>
            <p>暂无条款</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 签订合同区域 - 下半部分 -->
    <div class="sign-area mt-6 card shadow-sm">
      <div class="card-body">
        <h4 class="text-lg font-semibold text-gray-700 mb-4">签订合同</h4>

        <div class="mb-6">
          <label for="pdfFile" class="form-label block text-sm font-medium text-gray-700 mb-1">上传线下签订的PDF文件</label>
          <div class="relative">
            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
              <i class="fa fa-file-pdf text-gray-400"></i>
            </div>
            <input
                type="file"
                id="pdfFile"
                class="form-control pl-10 pr-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-green-500 focus:border-transparent"
                accept=".pdf"
                @change="handleFileUpload"
            >
          </div>
          <p v-if="fileName" class="mt-2 text-sm text-green-600">
            <i class="fa fa-check-circle mr-1"></i>已选择: {{ fileName }}
          </p>
        </div>

        <div class="d-flex gap-3 mb-6">
          <button
              @click="downloadContractPdf"
              class="btn btn-info flex-grow py-2.5 transition-all duration-200 hover:shadow-md"
              :disabled="loadingPdf"
          >
            <i class="fa fa-download mr-2"></i>下载合同内容PDF
          </button>
          <button
              @click="confirmSignContract"
              class="btn flex-grow py-2.5 transition-all duration-200 hover:shadow-md"
              :disabled="!fileName || loading"
              :class="fileName ? 'btn-success' : 'btn-gray'"
          >
            <i class="fa fa-check mr-2"></i>
            {{ fileName ? '确认签订合同' : '确认签订合同（请先选择文件）' }}
          </button>
        </div>

        <div v-if="uploadSuccess" class="alert alert-success bg-green-50 border-l-4 border-green-400 text-green-700 p-4">
          <div class="flex">
            <i class="fa fa-check-circle mr-3 mt-1"></i>
            <span>推送签订合同待用户确认成功！</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'

export default {
  name: 'ContractSignConfirm',
  setup() {
    const route = useRoute()
    const router = useRouter()

    const contractId = ref(route.params.contractId)
    const contract = ref(null)
    const clauses = ref([])
    const errorMessage = ref('')
    const loading = ref(true)
    const fileName = ref('')
    const uploadSuccess = ref(false)
    const loadingPdf = ref(false)

    // 状态映射表
    const statusMap = {
      "DRAFT": "草稿",
      "PENDING_REVIEW": "待审核",
      "REVIEW_FAILED": "审核失败",
      "PENDING_CONFIRMATION": "待确认",
      "CONFIRMED": "已确认",
      "COMPLETED": "已完成",
      "ARCHIVED": "已归档"
    }

    // 获取项目经理名称
    const projectManagerName = computed(() => {
      return contract.value?.projectManager?.name || '未指定'
    })

    // 获取合同详情
    const fetchContractDetails = () => {
      loading.value = true
      errorMessage.value = ''

      if (!contractId.value) {
        errorMessage.value = '缺少合同ID参数'
        setTimeout(() => {
          router.push('/employee/dashboard')
        }, 2000)
        loading.value = false
        return
      }

      axios.get(`/auth/contracts/${contractId.value}`)
          .then(response => {
            contract.value = response.data
          })
          .catch((err) => {
            console.error('获取合同详情失败', err)
            errorMessage.value = '获取合同详情失败，请重试'
          })
          .finally(() => {
            loading.value = false
          })
    }

    // 获取条款
    const fetchClauses = () => {
      if (!contractId.value) {
        console.log('合同ID不存在，无法获取条款')
        return
      }

      axios.get(`/auth/clauses/contract/${contractId.value}`)
          .then(response => {
            clauses.value = response.data
          })
          .catch((err) => {
            console.error('获取合同条款失败', err)
            errorMessage.value = '获取合同条款失败，请重试'
          })
    }

    // 处理文件上传
    const handleFileUpload = (event) => {
      const file = event.target.files[0]
      if (file && file.type === 'application/pdf') {
        fileName.value = file.name
        errorMessage.value = ''
      } else {
        fileName.value = ''
        errorMessage.value = '请选择有效的PDF文件'
      }
    }

    // 下载合同PDF
    const downloadContractPdf = () => {
      loadingPdf.value = true
      axios.get(`/auth/contracts/${contractId.value}/pdf`, {
        responseType: 'blob'
      })
          .then(response => {
            const url = window.URL.createObjectURL(new Blob([response.data]))
            const link = document.createElement('a')
            link.href = url
            link.setAttribute('download', `${contract.value?.name}.pdf`)
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
          })
          .catch(error => {
            console.error('下载PDF失败', error)
            errorMessage.value = '下载合同PDF失败，请重试'
          })
          .finally(() => {
            loadingPdf.value = false
          })
    }

    // 确认签订合同
    const confirmSignContract = () => {
      if (!fileName.value) {
        errorMessage.value = '请先上传线下签订的PDF文件'
        return
      }

      loading.value = true
      const formData = new FormData()
      const fileInput = document.getElementById('pdfFile')
      if (fileInput.files.length > 0) {
        formData.append('file', fileInput.files[0])
      }

      axios.post(`/auth/contracts/${contractId.value}/sign`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
          .then(() => {
            uploadSuccess.value = true
            errorMessage.value = ''
            // 成功后刷新合同状态
            setTimeout(() => {
              fetchContractDetails()
            }, 1000)
          })
          .catch(error => {
            console.error('签订合同失败', error)
            errorMessage.value = error.response?.data?.message || '签订合同失败，请重试'
          })
          .finally(() => {
            loading.value = false
          })
    }

    // 返回上一级
    const goBack = () => {
      router.go(-1)
    }

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleString()
    }

    // 格式化状态
    const formatStatus = (statusCode) => {
      return statusMap[statusCode] || statusCode
    }

    // 根据状态获取样式类
    const getStatusClass = (status) => {
      const classMap = {
        'DRAFT': 'bg-yellow-100 text-yellow-800',
        'PENDING_REVIEW': 'bg-blue-100 text-blue-800',
        'REVIEW_FAILED': 'bg-red-100 text-red-800',
        'PENDING_CONFIRMATION': 'bg-purple-100 text-purple-800',
        'CONFIRMED': 'bg-green-100 text-green-800',
        'COMPLETED': 'bg-teal-100 text-teal-800',
        'ARCHIVED': 'bg-gray-100 text-gray-800'
      }
      return classMap[status] || 'bg-gray-100 text-gray-800'
    }

    onMounted(() => {
      fetchContractDetails()
      fetchClauses()
    })

    return {
      contractId,
      contract,
      clauses,
      errorMessage,
      loading,
      fileName,
      uploadSuccess,
      loadingPdf,
      projectManagerName,
      goBack,
      formatDate,
      handleFileUpload,
      downloadContractPdf,
      confirmSignContract,
      formatStatus,
      getStatusClass
    }
  }
}
</script>

<style scoped>
/* 保持原有样式不变 */
.contract-sign-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.loading-indicator {
  min-height: 200px;
}

.spinner {
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-left-color: #42b983;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
  display: inline-block;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.error-message, .alert {
  display: flex;
  align-items: flex-start;
}

.card {
  border: 1px solid #e2e8f0;
  border-radius: 0.5rem;
  box-shadow: 0 1px 3px rgba(0,0,0,0.05);
}

.card-header {
  padding: 0.75rem 1.25rem;
  border-bottom: 1px solid #e2e8f0;
  background-color: #f8fafc;
  border-top-left-radius: 0.375rem;
  border-top-right-radius: 0.375rem;
}

.card-body {
  padding: 1.25rem;
}

.form-label {
  font-weight: 500;
  color: #4b5563;
}

.form-control {
  width: 100%;
  padding: 0.5rem 0.75rem;
  border: 1px solid #d1d5db;
  border-radius: 0.375rem;
  transition: all 0.2s;
}

.form-control:focus {
  outline: none;
  border-color: #42b983;
  box-shadow: 0 0 0 3px rgba(66, 185, 131, 0.2);
}

.btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 0.5rem 1rem;
  border-radius: 0.375rem;
  font-weight: 500;
  cursor: pointer;
  border: none;
  transition: all 0.2s;
}

.btn-info {
  background-color: #3b82f6;
  color: white;
}

.btn-info:hover {
  background-color: #2563eb;
  box-shadow: 0 4px 6px -1px rgba(59, 130, 246, 0.4);
}

.btn-success {
  background-color: #42b983;
  color: white;
}

.btn-success:hover {
  background-color: #369c6b;
  box-shadow: 0 4px 6px -1px rgba(66, 185, 131, 0.4);
}

.btn-secondary {
  background-color: #6c757d;
  color: white;
}

.btn-secondary:hover {
  background-color: #5a6268;
}

.btn-gray {
  background-color: #e5e7eb;
  color: #9ca3af;
  cursor: not-allowed;
}

.btn-gray:hover {
  background-color: #e5e7eb;
  box-shadow: none;
}

.contract-name {
  margin-bottom: 0.75rem;
}

.contract-info {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 1rem;
}

.clauses-section {
  margin-top: 1.5rem;
}

.empty-message {
  padding: 2rem;
  border: 2px dashed #e2e8f0;
  border-radius: 0.5rem;
}

.sign-area {
  margin-top: 1.5rem;
}
</style>